import { Tooltip } from 'antd';
import { DataNode } from 'antd/lib/tree';

import MyIcon from '@/components/MyIcon';
import pageStyles from '@/common/pageLayout.less';
import { getColorTextLoadMap, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { CreateTarget } from './CreateTarget';
import lodash from 'lodash';

// 采购办法
export const supplyWayList = [
  {
    value: 0,
    name: '月度计划',
  },
  {
    value: 1,
    name: '零星采购',
  },
  // {
  //   value: 2,
  //   name: '实验平台',
  // },
];

/** 采购类别 */
export const PURCHASE_Type = [
  { value: 0, name: '科研物资类' },
  { value: 1, name: '科研服务类' },
  { value: 2, name: '职能管理类' },
];

/** 对应科研物资类 */
export let KYWZ_Type = [
  { value: 0, name: '设备类' },
  { value: 1, name: '软件类' },
  { value: 2, name: '材料类' },
  { value: 3, name: '其他' },
];

/** 对应科研服务类 */
export let KYFW_Type = [
  { value: 0, name: '测试类' },
  { value: 1, name: '加工类' },
  { value: 2, name: '服务类' },
  { value: 3, name: '其他' },
];

/** 对应职能管理类 */
export let ZNGL_Type = [
  { value: 0, name: '货物类' },
  { value: 1, name: '服务类' },
  { value: 2, name: '工程类' },
  { value: 3, name: '其他' },
];

// <<<==========================采购申请状态===========================>>>START
/**`1000`起草*/
export const QC_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1000`;
/**`1001`标包整理【此状态已作废】*/
export const BBZL_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1001`;
/**`1002`审批中*/
export const SHZ_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1002`;
/**`1003`审批通过*/
export const SHTG_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1003`;
/**`1004`待采购*/
export const DCG_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1004`;
/**`1005`采购中*/
export const CGZ_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1005`;
/**`1006`采购完结*/
export const CGWJ_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1006`;
/**`1007`申请作废*/
export const ZF_SQSTATE = () => `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1007`;
// <<<==========================采购申请状态===========================>>>START

//  <<<==========================采购实施状态===========================>>>START
/**`1000`待编制*/
export const DBZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1000`;
//  <<<==========================采购实施状态===========================>>>START

// <<<==========================采购申请工作流===========================>>>START
/** 流程类别*/
export const SQ_flowBusinessType = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1003`;
/** 业务Controller【controller】*/
export const SQ_requestController = () => 'purchaseApplyController';
/** 工单类型【orderType】 */
export const SQ_orderType = () => `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1011`;
/** 业务流程类别(月度)*/
export const SQ_businessCategory = () => `${getTenantID()}${ILoadMapTypeAll.PURAPPLY_APPLY}1000`;
/** 业务流程类别(零星) */
export const SQ_LX_businessCategory = () => `${getTenantID()}${ILoadMapTypeAll.PURAPPLY_APPLY}1001`;
// <<<==========================采购申请工作流===========================>>>END

export const addOneAndPad = (str) => {
  // 将字符串转换成数字并加1
  let num: any = parseInt(str) + 1;
  // 检查数字是否是个位数
  if (num < 10) {
    // 在数字前面拼接一个字符串'0'
    num = '0' + num;
  }
  // 返回处理后的结果
  return num;
};

// <<<==========================意向公开工作流===========================>>>START
/**`起草state`*/
export const YXGK_STATE_QC = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1000`;
};
/**`审核中state`*/
export const YXGK_STATE_SHZ = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1001`;
};
/**`审核通过state`*/
export const YXGK_STATE_SHTG = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1002`;
};
/**`作废state`*/
export const YXGK_STATE_ZF = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1003`;
};
/** 流程相关&流程类别【category】*/
export const flowBusinessType = () => {
  return `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`;
};
/** 业务Controller【controller】*/
export const requestController = () => {
  return 'purchaseSourceIntentController';
};
/** 工单类型【orderType】 */
export const orderType = () => {
  return `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1019`;
};
/** 业务流程类别【businessCategory】 */
export const businessCategory = () => {
  return `${getTenantID()}${ILoadMapTypeAll.INTENTION_CATEGORY}1000`;
};
// <<<==========================意向公开工作流===========================>>>END

// <<<==========================采购方式变更===========================>>>START
/**`起草`*/
export const FSBG_STATE_QC = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1000`;
};
/**`审核中`*/
export const FSBG_STATE_SHZ = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1001`;
};
/**`成功`*/
export const FSBG_STATE_CG = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1002`;
};
/**`作废`*/
export const FSBG_STATE_ZF = () => {
  return `${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}1003`;
};
/** 业务Controller【controller】*/
export const BGrequestController = () => 'purchaseSourceChangeController';
/** 流程相关&流程类别【category】*/
export const BGflowBusinessType = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1002`;
/** 工单类型【orderType】 */
export const BGorderType = () => `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1013`;
/** 业务流程类别【businessCategory】【CHANGEPURCHASE_METHOD】 */
export const BGbusinessCategory = () => `${getTenantID()}${ILoadMapTypeAll.CHANGEPURCHASE_METHOD}1000`;
// <<<==========================采购方式变更===========================>>>END

// <<<==========================拟定采购方式两种父类===========================>>>STATE
/** 实验室自行组织 */
export const LaboratorySelfOrg = () => `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}1000`;
/** 政府集中采购 */
export const GoveCentralPurchse = () => `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}1001`;
// <<<==========================拟定采购方式两种父类===========================>>>END

export const getNowData = (nowdata): any[] => {
  const result = {};
  nowdata.forEach((item) => {
    const needMID = item.needMID;
    if (!result[needMID]) {
      // 如果结果对象中没有该 ID 的属性，则初始化为当前对象
      result[needMID] = { ...item };
    } else {
      // 如果结果对象中已经有该 ID 的属性，则将 sum 属性相加
      result[needMID].expectNum = (result[needMID].expectNum || 0) + item.expectNum;
      result[needMID].expectSum = (Number(result[needMID].expectSum) || 0) + Number(item.expectSum);
    }
  });
  // 将结果对象的值转换为数组
  const mergedArray = Object.values(result);
  return mergedArray;
};

export const negateMap = ['作废', '不同意'];
export const affirmMap = ['提交', '同意'];

/** 处理反显数据格式 */
export const handleReturnObjectData = (tempData) => {
  const clone_tempData = lodash.cloneDeep(tempData);
  tempData?.forEach((item, index) => {
    const target = new CreateTarget();
    target.addTarget(item?.mpurchaseNeedMaterials, 'materialID');
    const getTargets = target.getTarget(true);
    clone_tempData[index].mpurchaseNeedMaterials = getTargets;
  });
  return clone_tempData;
};

/**单个处理数据格式*/
export const handleOneObjectData = (data) => {
  const target = new CreateTarget();
  target.addTarget(data, 'materialID');
  const getTargets = target.getTarget(true);
  return getTargets;
};

/** 计算标的总价 */
export const getExpectSum = (tempData) => {
  // 设置计算标的预算总价
  const prices = tempData?.map((item: Record<string, any>) => {
    return item?.expectSum;
  });

  // 计算标的总价
  let expectSum: string = '0.00';
  if (prices?.length > 1) {
    // 多个标的加和
    expectSum = prices
      ?.reduce((prePrice: number, curPrice: number) => {
        return Number(prePrice) + Number(curPrice);
      })
      ?.toFixed(2);
  } else if (prices?.length == 1) {
    // 单个标的
    expectSum = Number(prices[0])?.toFixed(2);
  }

  return { expectSum };
};

/**判断值是否有两位小数点，没有则自动补零*/
export const formatDecimal = (val: any) => {
  // 不存在的话就返回'--'
  if (!val) return '--';
  // 将输入值转为数字，以确保处理的是数值类型
  const num = Number(val);
  // 如果转换后的数值是NaN，则直接返回原始值
  if (isNaN(num)) return '--';
  // 使用toFixed方法确保小数点后有两位，然后再转回字符串
  return num.toFixed(2) + '';
};

/**处理state无翻译*/
export const translateState = (state: string | null) => {
  if (!state) return '--';
  let str = '';
  switch (str == '') {
    case state == QC_SQSTATE():
      return (str = '起草');
    case state == BBZL_SQSTATE():
      return (str = '标包整理');
    case state == SHZ_SQSTATE():
      return (str = '审批中');
    case state == SHTG_SQSTATE():
      return (str = '审批通过');
    case state == DCG_SQSTATE():
      return (str = '待采购');
    case state == CGZ_SQSTATE():
      return (str = '采购中');
    case state == CGWJ_SQSTATE():
      return (str = '采购完结');
    case state == ZF_SQSTATE():
      return (str = '申请作废');
  }
  return '--';
};

export const onMaximumType = (array: Record<string, any>[]) => {
  if (!Array.isArray(array) || array.length === 0) {
    return null; // 处理无效输入
  }

  // 创建一个对象来存储 "aa" 值的出现次数
  const countMap = {};

  // 遍历数组，统计每个 "aa" 值的出现次数
  array?.forEach((item) => {
    if (item?.hasOwnProperty('supplyType')) {
      const aaValue = item?.supplyType;
      if (countMap?.hasOwnProperty(aaValue)) {
        countMap[aaValue]++;
      } else {
        countMap[aaValue] = 1;
      }
    }
  });

  // 找到出现次数最多的 "aa" 值
  let mostFrequentAA: any = null;
  let maxCount = 0;

  for (const aaValue in countMap) {
    if (countMap[aaValue] > maxCount) {
      mostFrequentAA = aaValue;
      maxCount = countMap[aaValue];
    }
  }

  return mostFrequentAA;
};

/** 处理BUTTON的变色问题 */
export const onMouseOut_ANTDBTN = (event: any) => {
  event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
};

/** columns内容渲染的方法【非字典】 */
export const ColumnsRenderFun = ({ isTooltip = true, text, textStyle = {}, event = undefined, record = {} }: Record<string, any>) => {
  return (
    <>
      <Tooltip title={isTooltip ? text : undefined}>
        <span className={pageStyles['over-flow-hidden']} onClick={event ? () => event(record) : undefined} style={textStyle}>
          {text == null || text == undefined || text == '' ? '--' : text}
        </span>
      </Tooltip>
    </>
  );
};

/** columns内容渲染的方法【字典】 */
export const DictionaryRenderFun = ({ isTooltip = false, text, textStyle = {}, event = undefined, record = {} }: Record<string, any>) => {
  const { colorText, color } = getColorTextLoadMap(text);
  return (
    <>
      <Tooltip title={isTooltip ? text : undefined}>
        <span className={pageStyles['over-flow-hidden']} onClick={event ? () => event(record) : undefined} style={{ color, ...textStyle }}>
          {colorText == null || colorText == undefined || colorText == '' ? '--' : colorText}
        </span>
      </Tooltip>
    </>
  );
};

/** 处理步骤条三--申请信息--table表格数据合并 */
export const SortAndGroupData = (data) => {
  // 根据 procureReal 字段进行分类
  const groupedByProcureReal = {};

  data.forEach((item) => {
    const procureReal = item.procureReal;
    if (!groupedByProcureReal[procureReal]) {
      groupedByProcureReal[procureReal] = [];
    }
    groupedByProcureReal[procureReal].push(item);
  });

  // // 对每个分类内的数据按照 packName 进行排序
  // for (const procureReal in groupedByProcureReal) {
  //   groupedByProcureReal[procureReal].sort((a, b) => a.packName.localeCompare(b.packName));
  // }

  // 合并所有分类的数据并保持原始顺序
  const finalResult = Object.values(groupedByProcureReal).reduce((result: any, items) => result.concat(items), []);

  return finalResult;
};

/**
 * 切换page的时候那标包信息的物料列表，但是里面可能会有重叠的【customNeedMatrials字段】,
 * 该方法是将里面的数据，全部扁平化，便于再次点击选择物料弹窗，做最大可采数量等计算
 *  */
export const processObjects = (inputArray: any) => {
  if (!inputArray && JSON.stringify(inputArray) == '[]') return [];

  // 声明一个变量来接收处理后的结果
  const resultArray: Record<string, any>[] = [];

  inputArray?.forEach((item: Record<string, any>) => {
    if (item.hasOwnProperty('customNeedMatrials') && Array.isArray(item.customNeedMatrials)) {
      item.customNeedMatrials?.forEach((ite: Record<string, any>) => {
        resultArray?.push(ite);
      });
    } else {
      resultArray?.push(item);
    }
  });

  // // 遍历输入数组中的每个对象
  // for (const obj of inputArray) {
  //   // 如果对象具有 customNeedMatrials 属性且它是一个数组
  //   if (obj.hasOwnProperty('customNeedMatrials') && Array.isArray(obj.customNeedMatrials)) {
  //     // 展开 customNeedMatrials 属性的值并放入结果数组
  //     resultArray.push(...obj?.customNeedMatrials);
  //   } else {
  //     // 否则，将当前对象放入结果数组
  //     resultArray.push(obj);
  //   }
  // }

  // 返回处理后的数组
  return resultArray;
};

/***
 * 审核状态
 * @param state
 * */
export const requirementApplicationFormat = (state: number | null | undefined) => {
  if (typeof state !== 'number') return '--';
  if (state == 1) {
    return <span style={{ color: '#0c880c' }}>通过</span>;
  } else {
    return <span style={{ color: '#e17ec7' }}>取消</span>;
  }
};

/**
 * @renderOverflowText
 * @description 处理文字溢出
 * @param text 值
 * @param isShowTooltip 是否溢出隐藏并且加Tooltip
 * @returns
 */
export const renderOverflowText = (text: string | number | null, isShowTooltip = false) => {
  const index = ['0', '1'].indexOf(String(text) || '');
  const info = {
    word: text ?? '--',
    color: '',
  };

  if (index != -1) {
    info.word = index == 1 ? '是' : '否';
    info.color = index == 1 ? '#409eff' : 'red';
  }
  if (isShowTooltip && info.word != '--') {
    return (
      <Tooltip title={info.word}>
        <span className={pageStyles['over-flow-hidden']} style={{ color: info.color }}>
          {info.word}
        </span>
      </Tooltip>
    );
  } else {
    return <span style={{ color: info.color }}>{info.word}</span>;
  }
};

/***
 * 审核状态 -- 处理  返回div
 * @param state
 * */
export const signStateOfRendering = (state: number | null | undefined) => {
  if (typeof state !== 'number') return '--';
  if (state == 0)
    return (
      <div>
        <span style={{ color: '#4246d1' }}>待审核</span>
      </div>
    );
  else if (state == 1)
    return (
      <div>
        <span style={{ color: '#1e9392' }}>通过</span>
      </div>
    );
  else if (state == 2)
    return (
      <div>
        <span style={{ color: '#9d3df0' }}>驳回</span>
      </div>
    );
  else
    return (
      <div>
        <span style={{ color: '#5c6f91' }}>作废</span>
      </div>
    );
};

/***
 *  -- 状态 -- 处理
 * @param state
 * */
export const stateOfRendering = (state: number | null | undefined, isShowIcon: boolean = true) => {
  if (typeof state !== 'number') return '--';
  if (state == 0) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#6812f2' }} />}
        <span style={{ color: '#6812f2' }}>起草</span>
      </div>
    );
  } else if (state == 1) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#2390fd' }} />}
        <span style={{ color: '#2390fd' }}>审核中</span>
      </div>
    );
  } else if (state == 2) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#59d6a5' }} />}
        <span style={{ color: '#59d6a5' }}>有效</span>
      </div>
    );
  } else {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#5c6f91' }} />}
        <span style={{ color: '#5c6f91' }}>无效</span>
      </div>
    );
  }
};

/**
 * setTableRowClassName 设置表格单双行类名
 */
export const setTableRowClassName = (_: Record<string, any>, index: number) => {
  return index % 2 == 0 ? 'double-row' : 'default-row';
};

/**
 * 排序
 * */
export const getSorter = (prev: Record<string, any>, next: Record<string, any>): number => (prev > next ? 1 : -1);

export const treeData: DataNode[] = [
  {
    title: '物料类型',
    key: 'WLLX',
    children: [
      {
        title: '工程类',
        key: '100100081000',
      },
      {
        title: '服务类',
        key: '100100081002',
      },
      {
        title: '货物类',
        key: '100100081001',
        children: [
          {
            title: '软件类',
            key: 'WLLX_HWL_FDJ',
          },
          {
            title: '设备类',
            key: 'WLLX_HWL_JS',
          },
          {
            title: '材料类',
            key: 'WLLX_HWL_CLL',
          },
        ],
      },
    ],
  },
];

export function combineObjects(array) {
  const resultArray: Record<string, any>[] = [];
  const processedIDs = new Set();

  array.forEach((obj) => {
    const { needID, planID, materialID, expectNum, inpNum } = obj;
    const uniqueID = `${needID}_${planID}_${materialID}`;

    if (!processedIDs.has(uniqueID)) {
      const matchingObjects = array.filter((o) => o.needID === needID && o.planID === planID && o.materialID === materialID);

      const totalExpectNum = matchingObjects.reduce((sum, o) => sum + o.expectNum, 0);

      // 额外加和具有 inpNum 属性的对象的 inpNum
      const totalInpNum = matchingObjects.reduce((sum, o) => (o.inpNum ? sum + o.inpNum : sum), 0);

      const combinedObject: Record<string, any> = {
        needID,
        planID,
        materialID,
        expectNum: totalExpectNum,
        newExpectNum: totalInpNum, // 新属性 newExpectNum 只计算具有 inpNum 属性的对象的总和
      };

      resultArray.push(combinedObject);
      processedIDs.add(uniqueID);
    }
  });

  return resultArray;
}
